package com.matt.service.courseV2.impl;

import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.domain.Children;
import com.matt.domain.Classes;
import com.matt.domain.courseV2.Milepost;
import com.matt.domain.courseV2.MilepostUser;
import com.matt.domain.courseV2.po.MilepostCardPO;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.DateUtil;
import com.matt.repository.ChildrenRepository;
import com.matt.repository.ClassesRepository;
import com.matt.repository.base.BaseNativeSqlRepository;
import com.matt.repository.courseV2.MilepostRepository;
import com.matt.repository.courseV2.MilepostUserRepository;
import com.matt.repository.courseV2.VendorCoursePackageRepository;
import com.matt.service.courseV2.MilepostService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class MilepostServiceImpl implements MilepostService {

    @Autowired
    private MilepostRepository milepostRepository;

    @Autowired
    private MilepostUserRepository milepostUserRepository;

    @Autowired
    private BaseNativeSqlRepository baseNativeSqlRepository;

    @Autowired
    private ChildrenRepository childrenRepository;

    @Autowired
    private ClassesRepository classesRepository;

    @Autowired
    protected MemVerificationCache cache;

    @Override
    public Map list(String childrenId, String timeAxis,String name, String states, String completeStates) {

        String sql = String.format("SELECT m.`name`,m.startTime,IFNULL(mu.url,'') url,IFNULL(mu.childrenId,'') childrenId, " +
                "IFNULL(mu.created,''),IFNULL(mu.leadingDay,'') leadingDay,IFNULL(mu.states,'') states ,IFNULL(mu.cardStates,'') cardStates " +
                " ,IFNULL(mu.childrenTime,'') childrenTime ,IFNULL(c.`name`,'')  childrenName,IFNULL(mu.id,'') id   " +
                " FROM tc_milepost  m LEFT JOIN  tc_milepost_user mu ON  m.id =  mu.milepostId LEFT JOIN  children c on mu.childrenId = c.id " +
                " and  mu.childrenId    = '%s'  where 1=1 ",childrenId );

        if (Objects.nonNull(timeAxis)) {
            sql += String.format(" and m.timeAxis  = '%s' ", timeAxis);
        }

        if (Objects.nonNull(name)) {
            sql += " and m.`name`  LIKE  concat('%', '"+name+"', '%')";
        }
        if (Objects.nonNull(states)) {
            if (StringUtils.equals(states,"0")){
                sql += String.format(" and mu.states  ='%s' ", states);
            }else {
                sql += " and mu.states  >0 ";
            }
        }

        if (Objects.nonNull(completeStates)) {
            sql += String.format(" and mu.states   ='%s' ", completeStates);
        }
        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);
        List<Map> mapList = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            Map map = new HashMap();
            map.put("name", objects.get(i)[0].toString());
            map.put("startTime", objects.get(i)[1].toString());
            map.put("url", objects.get(i)[2].toString());
            map.put("childrenId", objects.get(i)[3].toString());
            map.put("created", objects.get(i)[4].toString());
            map.put("leadingDay", objects.get(i)[5].toString());
            map.put("states", objects.get(i)[6].toString());
            map.put("cardStates", objects.get(i)[7].toString());
            map.put("childrenTime", objects.get(i)[8].toString());
            map.put("childrenName", objects.get(i)[9].toString());
            map.put("id", objects.get(i)[10].toString());
            mapList.add(map);
        }
        Map map = new HashMap();
        map.put("total",objects.size());
        map.put("list",mapList);
        return map;
    }

    @Override
    public MilepostUser add(String childrenId, String milepostId, String url) {
        Children children = childrenRepository.findByCrmClienteleId(childrenId);
        if (Objects.isNull(children)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "对象不存在");
        }
        Milepost milepost  = milepostRepository.getOne(milepostId);
        if (Objects.isNull(milepost)){
            throw  new BusinessException(ErrorCode.IS_TARGET, "对象不存在");
        }

        //出生到现在的月与天
        String m = DateUtil.birthdayMonthDay(new Date(),children.getBirthday());

        //出生到现在的总天数
        int day  =DateUtil.birthdayDay(new Date(),children.getBirthday())+1;

        Date date = children.getBirthday();
        date.setTime(date.getTime()+(day * (1000L*3600L*24L)));
        //超前多少天
        int d = DateUtil.dataDay(new Date(),date);

        MilepostUser milepostUser = new MilepostUser();
        milepostUser.setMilepostId(milepost.getId());
        milepostUser.setChildrenTime(m);
        milepostUser.setChildrenId(childrenId);
        milepostUser.setUrl(url);
        milepostUser.setLeadingDay(d);
        String states;
        if (milepost.getStartTime() <= day && milepost.getEndTime()  >= day){
            states = "1";
        }else if (milepost.getStartTime()  > day){
            states = "2";
        }else {
            states = "3";
        }
        milepostUser.setStates(states);
        milepostUserRepository.save(milepostUser);
        return milepostUser;
    }

    @Override
    public Map cardList(String classesId) {
        String sql = String.format("SELECT m.`name`,m.startTime,IFNULL(mu.url,'') url,IFNULL(mu.childrenId,'') childrenId, " +
                "IFNULL(mu.created,''),IFNULL(mu.leadingDay,'') leadingDay,IFNULL(mu.states,'') states ,IFNULL(mu.cardStates,'') cardStates " +
                " ,IFNULL(mu.childrenTime,'') childrenTime  ,IFNULL(c.`name`,'')  childrenName ,IFNULL(mu.id,'') id " +
                " FROM  tc_milepost_user mu LEFT JOIN  tc_milepost  m  ON  m.id =  mu.milepostId LEFT JOIN  children c on mu.childrenId = c.id " +
                " where  mu.classesId    = '%s' ",classesId);


        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);
        List<Map> mapList = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            Map map = new HashMap();
            map.put("name", objects.get(i)[0].toString());
            map.put("startTime", objects.get(i)[1].toString());
            map.put("url", objects.get(i)[2].toString());
            map.put("childrenId", objects.get(i)[3].toString());
            map.put("created", objects.get(i)[4].toString());
            map.put("leadingDay", objects.get(i)[5].toString());
            map.put("states", objects.get(i)[6].toString());
            map.put("cardStates", objects.get(i)[7].toString());
            map.put("childrenTime", objects.get(i)[8].toString());
            map.put("childrenName", objects.get(i)[9].toString());
            map.put("id", objects.get(i)[10].toString());
            mapList.add(map);
        }
        Map map = new HashMap();
        map.put("total",objects.size());
        map.put("list",mapList);
        return map;
    }

    @Override
    @Transactional
    public void addCard(List<MilepostCardPO>  milepostCard) {
        for (int i = 0; i <milepostCard.size() ; i++) {
            MilepostUser milepostUser   =  milepostUserRepository.getOne(milepostCard.get(i).getId());
            if (Objects.isNull(milepostUser)){
                throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
            }
            milepostUser.setCardUrl(milepostCard.get(i).getCardUrl());
            milepostUserRepository.save(milepostUser);
        }
    }





    @Override
    public List<Map> timeAxis() {
        String sql = " SELECT IFNULL(timeAxis,'') timeAxis   FROM  tc_milepost  GROUP BY timeAxis ";
        List<Object[]> objects = baseNativeSqlRepository.sqlArrayList(sql);
        List<Map> mapList = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++){
            Map map = new HashMap();
            map.put("timeAxis", objects.get(i));
            mapList.add(map);
        }
        return mapList;
    }
}
